<!-- 上传图片 -->
<script lang="ts" setup>
import { ref } from 'vue'
import { Plus as IconPlus } from '@element-plus/icons-vue'
import type { UploadRequestOptions } from 'element-plus'
// TODO test
import { uploadFiles } from '@/api/common'
import type { PropType } from 'vue'
import { watch } from 'vue'

const emits = defineEmits(['update:modelValue'])

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  height: {
    type: String,
    default: '150px'
  },
  width: {
    type: String,
    default: '150px'
  },
  limit: {
    type: Number,
    default: 4
  },
  modelValue: {
    type: Array as PropType<string[]>,
    default() {
      return [] as string[]
    }
  }
})

const imgPrefix = ref(import.meta.env.VITE_BASE_URL)
const uploadList = ref<string[]>([])
/**
 * 发起上传请求
 */
function requestFunc(options: UploadRequestOptions) {
  console.log(options.file)
  uploadFiles(options.file).then((res) => {
    const list: string[] = (res.data.data.fileName || []).map((url: string) => imgPrefix.value + '/file/download/' + url)
    uploadList.value.push(...list)
    emits('update:modelValue', uploadList.value)
  })
}
/**
 * 点击移除
 */
function removeClick(index: number) {
  uploadList.value.splice(index, 1)
  emits('update:modelValue', uploadList.value)
}

watch(props.modelValue, () => {
  uploadList.value = props.modelValue
})
</script>

<template>
  <el-upload :limit="limit" :disabled="disabled" multiple :show-file-list="false" accept="image/*" :http-request="requestFunc">
    <div class="upload-img-box" v-for="(url, index) in uploadList" :key="index">
      <el-button type="primary" size="mini" class="btn-remove" @click.stop="removeClick(index)">移除</el-button>
      <img :src="url" class="img-item" style="object-fit: contain" :style="`width:${width};height:${height};`" />
    </div>
    <div v-if="uploadList.length < limit" class="upload-icon" :style="`width:${width};height:${height};`">
      <el-icon :size="40" color="lightgray">
        <IconPlus />
      </el-icon>
    </div>
  </el-upload>
</template>

<style lang="scss" scoped>
.upload-img-box {
  position: relative;
  cursor: auto;
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .img-item {
    display: inline-block;
    border: 1px dashed rgba(153, 153, 153, 0.36);
    border-radius: 6px;
    overflow: hidden;
    margin-right: 10px;
  }
  .btn-remove {
    position: absolute;
    bottom: 0px;
    left: calc(50% - 5px);
    transform: translate(-50%, 0);
  }
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  text-align: center;
  border-radius: 6px;
  border: 1px dashed rgba(153, 153, 153, 0.36);
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
